#include <iostream>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include <cstring>

using namespace std;

#define N 3

class threadDate
{
public:
    threadDate(int number)
    {
        _threadname = "thread-" + to_string(number); // thread-0
    }

public:
    string _threadname;
};

string toHex(pthread_t tid)
{
    char buffer[128];
    snprintf(buffer,sizeof(buffer),"0x%x",tid);
    return buffer;
}

__thread int val = 100;

int* ptr = nullptr;
void* threadrun(void* argc)
{
    pthread_detach(pthread_self());
    int test = 0;
    threadDate* td = static_cast<threadDate*>(argc);
    
    if(td->_threadname == "thread-2") 
    {
        ptr = &test;
    }

    int i = 0;
    while(i < 10)
    {
        printf("pid : %d,tid : %s,threadname : %s,test : %d,&test : %p\n",
            getpid(),toHex(pthread_self()).c_str(),td->_threadname.c_str(),test,&test);
        sleep(1);
        val++;
        test++;
        i++;
    }
    delete td;
}


int main()
{
    vector<pthread_t> tids;
    //创建多线程
    for(int i = 0; i < N; i++)
    {
        pthread_t tid;
        threadDate* td = new threadDate(i);
        pthread_create(&tid,nullptr,threadrun,td);
        tids.push_back(tid);
        //sleep(1);
    }

    //线程分离
    // for (auto i : tids)
    // {
    //     pthread_detach(i);
    // }
 
    for (int i = 0; i < tids.size(); i++)
    {
        int n = pthread_join(tids[i], nullptr);
        cout << "n = " << n << ", who: " << toHex(tids[i]) 
           << ", " << strerror(n) << endl;
    }

    // cout <<"主线程拿到了thread-2的test地址 : " << ptr << endl;
    // for(int i = 0;i < tids.size();i++)
    // {
    //     pthread_join(tids[i],nullptr);
    // }
    return 0;
}